package com.dlc.felear.xiaoensale.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.dlc.felear.xiaoensale.entity.Msg;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.OkHttpManager;
import com.itdlc.android.library.utils.APPDidUtil;
import com.itdlc.android.library.utils.AppInfo;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class RegisterDevice {
    private static final String TAG = "RegisterDevice";
    private Context context;
    private static RegisterDevice intstance;
    private boolean isDone = false;
    private String deviceId;
    private String versionCode;

    private RegisterDevice(Context context) {
        this.context = context;
        versionCode = AppInfo.getLocalVersionName(context);
        deviceId = APPDidUtil.getAppDid();
    }

    public static RegisterDevice getIntstance(Context context) {
        if (intstance == null) {
            synchronized (RegisterDevice.class) {
                if (intstance == null) {
                    intstance = new RegisterDevice(context);
                }
            }
        }
        return intstance;
    }

    public void register() {
        if (isDone || !TextUtils.equals(versionCode, "1.01")) {
            return;
        }
        Map<String, Object> paramer = new HashMap<String, Object>();
        paramer.put("deviceId", deviceId);
        OkHttpManager.HttpPostJson(HttpApi.REGISTER_URL, paramer, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    Msg msg = JsonHelper.parserJson(response, Msg.class);
                    if (msg != null && msg.getCode() == 200) {
                        isDone = true;
                    } else if (msg != null && msg.getCode() == 400 && TextUtils.equals(msg.getMessage(), "设备名称或编码已存在")) {
                        isDone = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
